using Sunny.UI;
using System.Text;
using System.Text.Unicode;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace TouchSocket_TCP的使用
{
    public partial class FrmServer : UIForm
    {
        public FrmServer()
        {
            InitializeComponent();
        }
        private TcpService service;

        /// <summary>
        /// 打开服务器
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private async Task<bool> OpenServer(string ip, string port)
        {
            //1.实例化服务器
            service = new TcpService();

            //一堆服务器的事件
            service.Connecting = (client, e) =>
            {
                //做一些连接的显示操作
                this.Invoke(() =>
                {
                    this.txt_ServerRev.AppendText($"客户端{client.Id}:{client.IP}:{client.Port}正在连接中...{Environment.NewLine}");
                });
                return EasyTask.CompletedTask;

            };//有客户端正在连接
            service.Connected = (client, e) =>
            {
                this.Invoke(() =>
                {
                    this.txt_ServerRev.AppendText($"客户端{client.Id}:{client.IP}:{client.Port}连接成功!{Environment.NewLine}");

                    //显示在客户端列表里
                    this.lb_Clients.Items.Add($"{client.Id}:{client.IP}:{client.Port}");
                });

                return EasyTask.CompletedTask;

            };//有客户端成功连接
            service.Closing = (client, e) =>
            {
                this.Invoke(() =>
                {
                    this.txt_ServerRev.AppendText($"客户端{client.Id}:{client.IP}:{client.Port}正在断开连接...{Environment.NewLine}");


                });

                return EasyTask.CompletedTask;
            };//有客户端正在断开连接，只有当主动断开时才有效。
            service.Closed = (client, e) =>
            {
                this.Invoke(() =>
                {
                    this.txt_ServerRev.AppendText($"客户端{client.Id}:{client.IP}:{client.Port}已成功断开！{Environment.NewLine}");

                    //从客户端列表里移除
                    this.lb_Clients.Items.Remove($"{client.Id}:{client.IP}:{client.Port}");
                });

                return EasyTask.CompletedTask;
            };//有客户端断开连接
            service.Received = async (client, e) =>
            {
                //从客户端收到信息
                var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
                this.Invoke(() =>
                {
                    //信息显示在界面里
                    this.txt_ServerRev.AppendText($"接收到客户端{client.Id}:{client.IP}:{client.Port}信息:{mes}{Environment.NewLine}");
                });


                await EasyTask.CompletedTask;
            };

            //2.配置服务器
            await service.SetupAsync(new TouchSocketConfig()//载入配置
                 .SetListenIPHosts($"tcp://{ip}:{port}")//可以同时监听两个地址 $插值
                 .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                 {
                     a.AddConsoleLogger();//添加一个控制台日志注入（注意：在maui中控制台日志不可用）
                 }));

            //3.启动服务器
            await service.StartAsync();//启动

            //4.服务器启动结果
            if (service.ServerState != ServerState.Running)
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 打开服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_OpenServer_Click(object sender, EventArgs e)
        {
            //获取IP和端口
            string ip = txt_ServerIP.Text.Trim();
            string port = txt_ServerPort.Text.Trim();
            //校验处理
            if (!ip.IsIP4())
            {
                UIMessageTip.ShowWarning("请输入正确的IP地址！");
                return;
            }
            if (!port.IsInt())
            {
                UIMessageTip.ShowWarning("请输入正确的端口号！");
                return;
            }

            bool isOpen = await OpenServer(ip, port);
            if (isOpen)
            {
                UIMessageTip.ShowOk("服务器启动成功！");
            }
            else
            {
                UIMessageTip.ShowError("服务器启动失败！");
            }
        }

        /// <summary>
        /// 关闭服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_StopServer_Click(object sender, EventArgs e)
        {
            //关闭服务器  条件   1.服务器实例不为空 2.服务器处于运行状态
            if (service != null && service.ServerState == ServerState.Running)
            {
                service.StopAsync();
                UIMessageTip.ShowOk("服务器已关闭！");
            }
            else
            {
                UIMessageTip.ShowWarning("服务器未启动！");
            }
        }
        /// <summary>
        /// 发送消息到客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ServerSend_Click(object sender, EventArgs e)
        {
            //需要拿到客户端的ID

            //判断发送区域是否为空
            string msg = txt_ServerSend.Text.Trim();
            if (string.IsNullOrEmpty(msg))
            {
                UIMessageTip.ShowWarning("发送内容不能为空！");
                return;
            }

            //校验客户端列表是否为空
            if (this.lb_Clients.Items.Count == 0)
            {
                UIMessageTip.ShowWarning("没有客户端连接！");
                return;
            }

            //确保选中了客户端
            if (this.lb_Clients.SelectedIndex == -1)
            {
                UIMessageTip.ShowWarning("请先选择客户端！");
                return;
            }

            //直接这么写 会有问题
            string id = this.lb_Clients.SelectedItem.ToString().Split(':')[0];

            //发送消息
            service.SendAsync(id, Encoding.UTF8.GetBytes(msg));
        }

        /// <summary>
        /// 打开客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OpenClient_Click(object sender, EventArgs e)
        {
            FrmClient frm = new FrmClient();
            frm.Show();
        }

    }
}
